<template>
  <div class="public-stay-manage-action app-container">
    <div class="public-stay-manage-top">
      <div v-if="$route.query.action === 'add'">新增</div>
      <div v-else-if="$route.query.action === 'edit'">编辑</div>
      <div v-else-if="$route.query.action === 'detail'">详情</div>
      <div class="action-btn-box" v-if="$route.query.action !== 'detail'">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
        >确定</el-button>
        <el-button
          plain
          size="mini"
          @click="goBack"
        >取消</el-button>
      </div>
      <div class="action-btn-box" v-else>
        <el-button
          plain
          size="mini"
          @click="() => { this.$router.go(-1) }"
        >返回</el-button>
      </div>
    </div>
    <div class="public-stay-manage-content">
      <div class="public-stay-manage-left">
        <div class="detail-title">基本信息</div>
        <el-form :model="queryParams" :rules="rules" label-position="top" ref="queryForm">
          <div class="top">
            <div class="left">
              <el-form-item label="名称" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入名称"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  size="small"
                  style="width: 500px"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="地址" prop="address">
                <el-input
                  v-model="queryParams.address"
                  placeholder="请输入地址"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  size="small"
                  style="width: 500px"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="经纬度" prop="addressDetail">
                <el-input
                  v-model="queryParams.addressDetail"
                  placeholder="请输入经纬度(如：123, 123)"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  size="small"
                  style="width: 500px"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="标签" prop="tag">
                <el-input
                  v-model="queryParams.tag"
                  placeholder="请输入标签"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  size="small"
                  style="width: 500px"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="联系电话" prop="phone">
                <el-input
                  v-model="queryParams.phone"
                  placeholder="请输入联系电话"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  size="small"
                  style="width: 500px"
                >
                </el-input>
              </el-form-item>
            </div>
            <div class="right">
              <el-form-item label="所属景区" prop="jingquId">
                <el-select
                  v-model="queryParams.jingquId"
                  placeholder="请选择景区"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  filterable
                  size="small"
                  style="width: 500px"
                >
                  <el-option v-for="item in jingQuList" :key="item.value"
                  :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="类型" prop="type">
                <el-radio-group v-model="queryParams.type" :disabled="$route.query.action === 'detail'">
                  <el-radio label="jiudian">酒店</el-radio>
                  <el-radio label="minsu">民宿</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="营业时间" prop="businessTime">
                <el-time-picker
                  is-range
                  v-model="queryParams.businessTime"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择营业时间">
                </el-time-picker>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select
                  v-model="queryParams.status"
                  placeholder="请选择状态"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  filterable
                  size="small"
                  style="width: 500px"
                >
                  <el-option v-for="item in dictList" :key="item.dictValue"
                  :label="item.dictLabel" :value="item.dictValue">
                  </el-option>
                </el-select>
              </el-form-item>

            </div>
          </div>
          <div class="bottom">
            <div class="left">
              <el-form-item label="酒店/民宿图片" required>
                <div class="upload-box">
                  <div class="file-box-view">
                    <el-image
                      v-if="fileData.img"
                      :src="fileData.img"
                      :preview-src-list="[fileData.img]"
                    >
                    </el-image>
                  </div>
                  <el-upload
                      v-if="$route.query.action !== 'detail'"
                      :action="uploadUrl"
                      list-type="picture-card"
                      :before-upload="handleBeforeUpload"
                      :on-success="(response) => handleUploadSuccess('img', response)"
                      :on-error="handleUploadError"
                      :on-remove="onRemoveHandel('img')"
                      :headers="headers"
                      :show-file-list="false"
                    >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </div>
              </el-form-item>
                  <!-- :show-file-list="false" -->
              <el-form-item label="配套设施" required>
                <div class="upload-box">
                  <div class="file-box-view">
                    <el-image
                      v-if="fileData.supportingImg"
                      :src="fileData.supportingImg"
                      :preview-src-list="[fileData.supportingImg]"
                    >
                    </el-image>
                  </div>
                  <el-upload
                      v-if="$route.query.action !== 'detail'"
                      :action="uploadUrl"
                      list-type="picture-card"
                      :before-upload="handleBeforeUpload"
                      :on-success="(response) => handleUploadSuccess('supportingImg', response)"
                      :on-error="handleUploadError"
                      :on-remove="onRemoveHandel('supportingImg')"
                      :headers="headers"
                      :show-file-list="false"
                    >
                      <i class="el-icon-plus"></i>
                  </el-upload>
                </div>
              </el-form-item>
            </div>
            <div class="right">
              <el-form-item label="酒店政策" required>
                <div class="upload-box">
                  <div class="file-box-view">
                    <el-image
                      v-if="fileData.policyImg"
                      :src="fileData.policyImg"
                      :preview-src-list="[fileData.policyImg]"
                    >
                    </el-image>
                  </div>
                  <el-upload
                      v-if="$route.query.action !== 'detail'"
                      :action="uploadUrl"
                      list-type="picture-card"
                      :before-upload="handleBeforeUpload"
                      :on-success="(response) => handleUploadSuccess('policyImg', response)"
                      :on-error="handleUploadError"
                      :on-remove="onRemoveHandel('policyImg')"
                      :headers="headers"
                      :show-file-list="false"
                    >
                      <i class="el-icon-plus"></i>
                  </el-upload>
                </div>
              </el-form-item>
              <el-form-item label="营业执照" required>
                <div class="upload-box">
                  <div class="file-box-view">
                    <el-image
                      v-if="fileData.businessLicenseImg"
                      :src="fileData.businessLicenseImg"
                      :preview-src-list="[fileData.businessLicenseImg]"
                    >
                    </el-image>
                  </div>
                  <el-upload
                      v-if="$route.query.action !== 'detail'"
                      :action="uploadUrl"
                      list-type="picture-card"
                      :before-upload="handleBeforeUpload"
                      :on-success="(response) => handleUploadSuccess('businessLicenseImg', response)"
                      :on-error="handleUploadError"
                      :on-remove="onRemoveHandel('businessLicenseImg')"
                      :headers="headers"
                      :show-file-list="false"
                    >
                      <i class="el-icon-plus"></i>
                  </el-upload>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </div>

  </div>
</template>

<script>
import { updateFn, add, list } from "@/api/publicService/stayManage";
import { dictFn } from "@/api/common";
import moment from 'moment'
import { getToken } from "@/utils/auth";
import {
  jingQuListApi, // 获取所有景区列表
} from "@/api/YApi/scenicSpot";

export default {
  name: "Logininfor",
  data() {
    return { 
      rules: {
          type: [
            { required: true, message: '请选择类型', trigger: 'change' }
          ],
          jingquId: [
            { required: true, message: '请选择景区', trigger: 'change' }
          ],
          status: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
          img: [
            { required: true, message: '请上传图片', trigger: 'change' }
          ],
          policyImg: [
            { required: true, message: '请上传图片', trigger: 'change' }
          ],
          supportingImg: [
            { required: true, message: '请上传图片', trigger: 'change' }
          ],
          address: [
            { required: true, message: '请输入地址', trigger: 'change' }
          ],
          tag: [
            { required: true, message: '请输入标签', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请输入名称', trigger: 'change' }
          ],
          phone: [
            { required: true, message: '请输入联系电话', trigger: 'change' }
          ],
          addressDetail: [
            { required: true, message: '请输入经纬度（如：123,123）', trigger: 'change' }
          ],
          businessTime: [
            { required: true, message: '请选择营业时间', trigger: 'change' }
          ],
      },
      // 遮罩层
      loading: true,
      uploadUrl: window.serverAPI.url + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploadFileLoading: false,
      jingQuList: [],
      dictList: [],
      fileData: {
        img: undefined,
        policyImg: undefined,
        supportingImg: undefined,
        businessLicenseImg: undefined,
      },
      // 查询参数
      queryParams: {
        address: undefined,
        jingquId: undefined,
        name: undefined,
        phone: undefined,
        type: undefined,
        addressDetail: undefined,
        status: undefined,
        tag: undefined,
        id: undefined,
      }
    };
  },
  created() {
    this.getJingQuList()
    this.getDict()
    this.$route.query.id && this.getList();
  },
  methods: {
    getList() {
      let {pageNum, pageSize, name, id} = this.$route.query
      list({
        pageNum, pageSize, name
      }).then(res => {
        let arr = res?.data?.rows || []
        let currentObj = arr.filter(item => item.id == id)?.[0] || {};
        let businessTime = currentObj?.businessTime ? currentObj?.businessTime?.split('-')?.map(item => {
          return moment(moment().format('YYYY-MM-DD') + ' ' + item).toDate()
        }) : []
        
        this.queryParams = {
          address: currentObj?.address || undefined,
          jingquId: currentObj?.jingquId || undefined,
          name: currentObj?.name || undefined,
          phone: currentObj?.phone || undefined,
          type: currentObj?.type || undefined,
          status: currentObj?.status || undefined,
          tag: currentObj?.tag || undefined,
          addressDetail: currentObj?.addressDetail || undefined,
          businessTime: businessTime || undefined,
          id: currentObj?.id || undefined,
        };
        this.fileData = {
          img: currentObj?.img || undefined,
          policyImg: currentObj?.policyImg || undefined,
          supportingImg: currentObj?.supportingImg || undefined,
          businessLicenseImg: currentObj?.businessLicenseImg || undefined,
        };

      });
    },
    getDict() {
      dictFn({
        pageNum: 1,
        pageSize: 100,
        reasonable: true,
        dictType: 'business_status'
      }).then(res => {
        this.dictList = res?.rows || []
      });
    },
    // 景区列表
    getJingQuList() {
      jingQuListApi()
        .then((res) => {
          if (res.code === 200) {
            this.jingQuList = res.data.map((v) => {
              return {
                value: v.jingquId,
                label: v.jingquName,
              };
            });
          }
        })
    },
    // 使用 before-upload 限制用户上传的图片格式和大小。
    handleBeforeUpload(file) {
      // 校检文件大小
      const isLt = file.size / 1024 / 1024 < 8;
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过8MB!`);
        return false;
      }
      // 检验格式
      let type = file.type;
      let jpg = type.indexOf("jpg");
      let png = type.indexOf("png");
      let jpeg = type.indexOf("jpeg");
      if (jpg == -1 && png == -1 && jpeg == -1) {
        this.$message.error(`上传文件格式为jpg，png，jpeg!`);
        return false;
      }

      return true;
    },

    // 文件上传成功钩子
    handleUploadSuccess(param, response) {
      if (response.code === 200) {
        this.fileData[param] = response.data.url
      }
    },

    // 删除已上传的文件
    onRemoveHandel(param) {
      this.queryParams[param] = ''
    },

    // 文件上传失败
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
    handleAdd() {
      console.log(this.queryParams);
      this.$refs.queryForm.validate((tag) => {
        if (tag) {
          let imgArr = ['img', 'supportingImg', 'policyImg', 'businessLicenseImg']
          let arr = imgArr.filter(item => this.fileData[item])
          if (arr.length !== 4) {
            return this.$message.error("请上传图片");
          } else {
            let fun = this.$route.query.id ? updateFn : add
            fun({
              ...this.queryParams,
              businessTime: `${moment(this.queryParams.businessTime[0]).format('hh:mm:ss')}-${moment(this.queryParams.businessTime[1]).format('hh:mm:ss')}`,
              ...this.fileData,
            }).then(res => {
              if (res?.code === 200) {
                this.$message.success("保存成功");
                this.goBack();
              } else {
                this.$message.error(res?.msg);
              }
            })
          }
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
  }
};
</script>


<style rel="stylesheet/scss" lang="scss">
.public-stay-manage-action {
  .public-stay-manage-top {
    border-bottom: 1px solid #F2F3F5;
    display: flex;
    justify-content: space-between;
    padding: 12px;
    align-items: center;
  }
  .public-stay-manage-content {
    .detail-title {
      position: relative;
      padding-left: 12px;
      padding-block: 20px;
      &::after {
        content: '';
        width: 4px;
        height: 16px;
        background: #3370FF;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        margin: auto 0;

      }
    }
  }
  .top, .bottom {
    display: flex;
    .left {
      width: 550px;
    }
    .right {
      flex: 1;
    }
  }
  .upload-box {
    display: flex;
    .file-box-view{
      height: 146px;
      width: 146px;
      margin-right: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      img{
        max-height: 100px;
        max-width: 100px;
      }
    }
  }
}
</style>